package com.fgs.common.utils;

import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.lang.ref.WeakReference;

/**
 * @author fgs
 * @date 2020/4/17
 * @description
 **/

public class CountDownTimerUtil extends CountDownTimer {

    private WeakReference<TextView> mTextView;

    public CountDownTimerUtil(TextView textView, long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        mTextView = new WeakReference(textView);

    }

    @Override
    public void onTick(long millisUntilFinished) {

        //用弱引用 先判空 避免崩溃
        if (mTextView.get() == null) {
            timeCancel();
            return;
        }

        mTextView.get().setEnabled(false);
        mTextView.get().setText("再次发送(" + millisUntilFinished / 1000 + ")");
    }

    @Override
    public void onFinish() {
        //用弱引用 先判空 避免崩溃
        if (mTextView.get() == null) {
            timeCancel();
            return;
        }
        mTextView.get().setEnabled(true);
        mTextView.get().setText("重新获取");

    }

    public void timeCancel() {
        if (this != null) {
            this.cancel();
        }
    }
}
